<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="机器人ID" prop="uid">
        <el-input
          v-model="queryParams.Uid"
          placeholder="请输入机器人唯一ID"
          clearable
          @keyup.enter.native="handleQuery"
          class="no-wrap-input"
        />
      </el-form-item>

      <el-form-item label="创建时间" prop="dt">
        <el-input
          v-model="queryParams.dt"
          placeholder="请输入创建时间"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:robot:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:robot:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="robotList" @selection-change="handleSelectionChange">
      <el-table-column label="机器人ID" align="center" prop="uid" />
      <el-table-column label="机器人名称" align="center" prop="name" />
      <el-table-column label="机器人头像" align="center" prop="portrait" >
              <template slot-scope="scope">
          <img 
            v-if="scope.row.portrait" 
            :src="getImageUrl(scope.row.portrait)" 
            style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;"
            @error="handleImageError"
          />
          <el-avatar v-else :size="40" icon="el-icon-user-solid"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="机器人服务器地址" align="center" prop="callback" />
      <el-table-column label="配置信息" align="center" prop="extra" />
     
      <el-table-column label="创建时间" align="center" prop="dt" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:robot:edit']"
          >修改</el-button>
       
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:robot:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改机器人对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="机器人名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item label="机器人密码" prop="secret">
          <el-input v-model="form.secret" type="password" placeholder="请输入机器人密码" show-password />
        </el-form-item>
        <el-form-item label="机器人头像" prop="portrait">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/*"
          >
            <img 
              v-if="form.portrait" 
              :src="getImageUrl(form.portrait)" 
              class="avatar" 
              @error="handleImageError"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div v-if="form.portrait" class="avatar-url-display">
            <el-button size="mini" type="text" @click="clearAvatar">清除头像</el-button>
          </div>
        </el-form-item>
        <el-form-item label="服务器地址" prop="callback">
          <el-input v-model="form.callback" placeholder="请输入服务器地址" />
        </el-form-item>
        
        <el-form-item label="配置信息" prop="extra">
          <el-input 
            v-model="form.extra" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入配置信息"
          />
        </el-form-item>

        
        <!-- <el-form-item label="状态" prop="State">
          <el-radio-group v-model="form.State">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRobot, getRobot, delRobot, addRobot, updateRobot } from "@/api/zl/robot"
import request from "@/utils/request"

export default {
  name: "Robot",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      robotList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
       // 文件上传配置
      upload: {
        // 设置上传的请求头部
        headers: {},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        uid: null,
        owner: null,
        secret: null,
        callback: null,
        state: null,
        extra: null,
        dt: null,
        portrait: null
      },
      // 表单参数
      form: {
        id: null,
        uid: null,
        name: null,
        secret: null,
        serverAddress: null,
        extra: null,
        callback: null,
        loginPassword: null,
        owner: null,
        state: null,
        dt: null,
        portrait: null

      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "机器人名称不能为空", trigger: "blur" }
        ],
       uid: [
          { required: true, message: "机器人ID不能为空", trigger: "blur" }
        ],
        secret: [
          { required: true, message: "机器人密码不能为空", trigger: "blur" }
        ],
        serverAddress: [
          { required: true, message: "服务器地址不能为空", trigger: "blur" }
        ],
        callback: [
          { required: true, message: "机器人登录地址不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList();
     // 在组件创建后设置上传headers
    this.upload.headers = { Authorization: "Bearer " + this.getToken() };
  },
  methods: {
      /** 获取token */
    getToken() {
      return this.$store.getters.token;
    },
    
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listRobot(this.queryParams).then(response => {
        this.robotList = response.rows
        this.total = parseInt(response.total) || 0
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        Uid: null,
        Name: null,
        Secret: null,
        ServerAddress: null,
        Extra: null,
        Callback: null,
        LoginPassword: null,
        Owner: null,
        State: 0, // 默认为正常状态
        Dt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加机器人"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getRobot(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改机器人"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRobot(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addRobot(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除机器人编号为"' + ids + '"的数据项？').then(function() {
        return delRobot(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/robot/export', {
        ...this.queryParams
      }, `robot_${new Date().getTime()}.xlsx`)
    },
    /** 状态切换操作 */
    handleStatusChange(row) {
      const newState = row.State === 0 ? 1 : 0
      const statusText = newState === 0 ? '启用' : '禁用'
      
      this.$modal.confirm(`是否确认${statusText}机器人"${row.Name}"？`).then(() => {
        const updateData = {
          ...row,
          State: newState
        }
        
        updateRobot(updateData).then(response => {
          this.$modal.msgSuccess(`${statusText}成功`)
          this.getList()
        }).catch(() => {
          this.$modal.msgError(`${statusText}失败`)
        })
      }).catch(() => {})
    },
       /** 图片加载错误处理 */
    handleImageError(event) {
      // 图片加载失败时隐藏img标签
      event.target.style.display = 'none'
    },
    /** 获取图片完整URL */
    getImageUrl(url) {
      if (!url) return ''
      // 清理URL中的空格和反引号
      url = url.trim().replace(/`/g, '');

      // 如果是OSS的完整URL，通过后端下载接口访问
      if (url.startsWith('https://') && url.includes('aliyuncs.com')) {
        return process.env.VUE_APP_BASE_API + '/common/download?fileName=' + encodeURIComponent(url) + '&delete=false'
      }
      
      // 如果已经是完整的HTTP/HTTPS URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
      }
      
      // 否则拼接BASE_API
      return process.env.VUE_APP_BASE_API + url
    },
    /** 头像上传成功处理 */
    handleAvatarSuccess(res, file) {
      console.log('上传响应:', res);
      
      if (res.code === 200) {
        // 后端返回的是完整的阿里云OSS URL，需要清理空格和反引号
        let avatarUrl =  res.url;
        let avatarUrlPath =  res.fileName;

        
        // 清理URL中的空格、反引号和双引号
        if (avatarUrl) {
          avatarUrl = avatarUrl.trim().replace(/[`"]/g, '');
        }
         if (avatarUrlPath) {
          avatarUrlPath = avatarUrlPath.trim().replace(/[`"]/g, '');
        }
        
        this.form.portrait = avatarUrl;
        this.form.portraitPath = avatarUrlPath;

        this.$message.success('头像上传成功');
        
        // 强制更新视图
        this.$nextTick(() => {
          this.$forceUpdate();
        });
      } else {
        this.$message.error(res.msg || '上传失败');
      }
    },
    /** 头像上传前的校验 */
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    /** 清除头像 */
    clearAvatar() {
        if (this.form.portraitPath) {
        console.log('当前头像URL:', this.form.portraitPath);
        // 调用后端删除文件接口
        this.deleteFile(this.form.portraitPath).then(() => {
          this.form.portrait = null
          this.$modal.msgSuccess("头像已清除")
        }).catch(() => {
          // 即使删除失败也清除表单字段
          this.form.portraitPath = null
          this.$modal.msgSuccess("头像已清除")
        });
      }
      
      // 清除表单中的头像字段
      this.form.portrait = '';
      
      // 强制更新视图
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
        /** 删除文件 */
    deleteFile(fileName) {
      return request({
        url: '/common/delete',
        method: 'post',
        data: fileName,
        headers: {
          'Content-Type': 'text/plain'
        }
      })
    }
  }
}
</script>

<style scoped>
.no-wrap-input {
  white-space: nowrap;
}
.no-wrap-input input {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: block;
}
</style>
